<?php

namespace App\Http\Controllers\Web\Buyer;

use App\ConstDir\ErrorConst;
use App\Http\Controllers\Web\BaseController;
use App\Repository\Models\User;
use App\Repository\Models\ItemsInformation;
use App\Repository\Repositories\Interfaces\AddressRepository;
use App\Repository\Repositories\Interfaces\InvoicesRepository;
use App\Repository\Repositories\Interfaces\ItemsInformationRepository;
use App\Repository\Repositories\Interfaces\ItemsProductsRepository;
use App\Repository\Repositories\Interfaces\OrdersRepository;
use App\Repository\Repositories\Interfaces\UserInvoiceRepository;
use Illuminate\Http\Request;

/**
 *
 * 卖家配单管理
 * @package App\Http\Controllers\Backend
 */
class ItemsInformationController extends BaseController
{
    protected $items;
    protected $request;
    protected $sp_uid;
    protected $shop_id;

    public function __construct(ItemsInformationRepository $items,Request $request)
    {
        parent::__construct();
        $this->request=$request;
        $this->items = $items;
        $this->sp_uid =array_get($this->user, 'id');
        $this->shop_id =array_get($this->shop_id, 'shop_id');
//        //用户只能操作自身所属数据
        $this->items->scopeQuery(function ($query) {
            return $query->where('buyer_id',$this->sp_uid);
        });
    }

    public function index(OrdersRepository $order)
    {
        $orders=$order->with(['items_products','items_information'])->scopeQuery(function($sql){
            return $sql->select('id','order_status','order_code','order_money','created_at')->where('order_type',4)->where('user_id',$this->sp_uid);
        })->paginate($this->perPage);

        return $this->success(ErrorConst::SUCCESS_CODE_MSG, $orders, true);
    }

    public function show($id){

        $items = $this->items->with(['items_products'])->with(['orders'=>function($sql){
            $sql->select('id','order_code','order_status');
        }])->with(['sellerCompanyAddr'=>function($sql){
            $sql->select('user_id','company_address');
        }])->find($id);

        $items['data']['quote_contain']=json_decode($items['data']['quote_contain'],true);
        $items['data']['quote_trade_time']=json_decode($items['data']['quote_trade_time'],true);
        if($items['data']['quote_trade_time'][0]==0){
            $items['data']['quote_trade_time']=$items['data']['quote_trade_time'][1];
        }else{
            $items['data']['quote_trade_time']=date('Y-m-d',strtotime($items['data']['created_at'])+$items['data']['quote_trade_time'][0]*60*60*24);
        }
        return $this->success(ErrorConst::SUCCESS_CODE_MSG, $items, false);
    }

    /**
     * @param ItemsProductsRepository $itemsProduct
     * @return \Illuminate\Support\Collection
     * 买家 配单下单
     */
    public function store(ItemsProductsRepository $itemsProduct){

        $all=$this->request->all();
        $buyer=User::query()->where('phone',$all['buyer_phone'])->get(['id','name','phone'])->toArray();

        if($buyer){
            $buyer_id=$buyer[0]['id'];
        }else{
            return $this->error(ErrorConst::FAILED_CODE_MSG);
        }
        $quote_trade_time=[
            0=>$all['delivery_time'],
            1=>isset($all['otherTime'])?$all['otherTime']:'',
        ];
        $product=[];
        $other_product=[];
        $goods_total=0;//商品总费用
        $other_total=0;//其它总费用
        if(!empty($all['append_goods_name'])){//商品费用
            foreach($all['append_goods_name'] as $k=>$v){
                $product[$k]['product_name']=$v;
                $product[$k]['brand']=$all['append_goods_brand'][$k];
                $product[$k]['model']=$all['append_goods_model'][$k];
                $product[$k]['num']=$all['append_goods_num'][$k];
                $product[$k]['price']=$all['append_goods_univalent'][$k];
                $product[$k]['type']=1;
                $goods_total+=($all['append_goods_num'][$k]*$all['append_goods_univalent'][$k]);
            }
        }
        if(!empty($all['append_cost_name'])){//其它费用
            foreach($all['append_cost_name'] as $k=>$v){
                $other_product[$k]['product_name']=$v;
                $other_product[$k]['num']=$all['append_cost_num'][$k];
                $other_product[$k]['price']=$all['append_cost_univalent'][$k];
                $other_product[$k]['type']=2;
                $other_total+=($all['append_cost_num'][$k]*$all['append_cost_univalent'][$k]);
            }
        }
        $goods_total=sprintf("%.2f",$goods_total);
        $other_total=sprintf("%.2f",$other_total);
        $data=[
            'buyer_id'=>$buyer_id,
            'buyer_phone' => $all['buyer_phone'],
            'buyer_contact' =>  $all['buyer_contact'],
            'buyer_company' =>$all['buyer_company'],
            'quote_contain' => json_encode($all['quote_contain']),//报价要素-价格包含
            'seller_phone' =>$all['seller_phone'],
            'seller_contact' => $all['seller_contact'],
            'seller_id' => $this->sp_uid ,
            'seller_company' => $all['seller_company'],
            'project_addr'=>$all['province_text'].$all['city_text'],
            'quote_trade_time'=> json_encode($quote_trade_time),//报价要素-交货时间
            'product'=>$product,
            'other_product'=>$other_product,
            'goods_total'=>$goods_total,
            'other_total'=>$other_total,
            'all_total'=>$goods_total+$other_total,
        ];

        \DB::beginTransaction();
        try{
            //生成订单

            $items = $this->items->create($data);

            if(!empty($data['product'])){
                foreach($data['product'] as $k=>$v){
                  $data['product'][$k]['item_id']=$items['data']['id'];
                   $itemsProduct->create($data['product'][$k]);
                }
            }

            if(!empty($data['other_product'])){
                foreach($data['other_product'] as $k=>$v){
                    $data['other_product'][$k]['item_id']=$items['data']['id'];
                    $itemsProduct->create($data['other_product'][$k]);
                }
            }

            \DB::commit();
        }catch (\Exception $e){
            \DB::rollback(); //事务回滚;
            return $this->error(ErrorConst::FAILED_CODE_MSG);
        }
        return $this->success(ErrorConst::SUCCESS_CODE_MSG, $data, false);

    }
    /**
     * 通过 item_code 获取 配单总金额
     * */
    public function getPaymentTotal(){
        try{

            $this->validate($this->request, [
                'item_code' => 'required'
            ]);

            $return = [];
            $code = $this->request->get('item_code');
            $items = ItemsInformation::query()->where('item_code',$code)->get()->toArray();
            if (!is_null($items) && isset($items[0])){
                $return = $items[0];
            }
        }catch (\Exception $e){
            return $this->error($e->getMessage());
        }

        return $this->success(ErrorConst::SUCCESS_CODE_MSG, $return, false);
    }

    /**
     * 配单支付页
     * @param $id
     */
    public function item_order(OrdersRepository $order){
        $data=$this->request->all();
        $orders=$order->with(['items_information','items_products'])->find($data['id']);

        return $this->success(ErrorConst::SUCCESS_CODE_MSG, $orders['data']);

    }

    /**
     * 去付款更新收货地址和发票
     * @param $id
     */
    public function item_store(OrdersRepository $order,AddressRepository $address,UserInvoiceRepository $user_invoice_repo,InvoicesRepository $invoices_repo){
        $data=$this->request->all();

        $orders=$order->find($data['id']);
//        return $this->success(ErrorConst::SUCCESS_CODE_MSG, $orders['data']);

        if(!isset($orders['data'])){
            return $this->success(ErrorConst::FAILED_CODE_MSG);
        }
        //地址
        $address = $address->find($data['address_id'], ['receiver', 'phone', 'address']);
        $data=$data+$address['data'];

        //发票信息公共部分
        if(!empty($data['invoices'])){
            $invoices = $user_invoice_repo->find($data['invoices'], [
                'id', 'invoice_message', 'invoice_type', 'invoice_title', 'tax_code', 'invoice_address',
                'invoice_tel', 'invoice_bank', 'invoice_account', 'post_address', 'post_contacts', 'post_tel'
            ]);
            $data['invoices']=$invoices['data'];

        }else{
            $invoices = [];
        }

        //发票创建
        if(!empty($data['invoices'])){
            $data['invoices']['invoice_price'] = $orders['data']['order_money'];
            $data['invoices']['user_id'] = $this->sp_uid;
            $data['invoices']['order_code'] = $orders['data']['order_code'];
            $invoices_repo->create($data['invoices']);
        }

        $orders=$order->update($data,$data['id']);

        return $this->success(ErrorConst::SUCCESS_CODE_MSG, $orders['data']);

    }

    public function buyer_index(OrdersRepository $order)
    {
        $orders=$order->with(['items_products','items_information'])->scopeQuery(function($sql){
            return $sql->select('id','order_status','order_code','order_money','created_at')->where('order_type',4)->where('user_id',$this->sp_uid)->limit(1);
        })->all();

        return $this->success(ErrorConst::SUCCESS_CODE_MSG, $orders['data'], true);
    }

}
